package com.asen.business.commons.service.impl;

import com.asen.business.commons.domain.Bill;
import com.asen.business.commons.service.BillService;
import com.asen.commons.core.base.domain.BaseEntry;
import com.asen.commons.enums.ServiceNameEnum;
import com.asen.commons.core.base.service.impl.AbstractGenericServiceImpl;
import com.asen.commons.core.meta.dao.Condition;
import com.asen.commons.core.meta.entity.FieldObject;
import com.asen.commons.exception.ServiceException;
import com.asen.commons.utils.BaseAssert;
import com.asen.commons.utils.RestUtils;
import com.asen.commons.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * 核心单据service抽象类
 *
 * @author Gary
 * @version 1.0
 * @date 2018-12-09
 */
@Slf4j
public abstract class AbstractBillServiceImpl<T extends Bill> extends AbstractGenericServiceImpl<T> implements BillService<T> {

    @Override
    public void checkDupByNumber(Long id, String number) throws Exception {
        if (StringUtils.isEmpty(number)) {
            return;
        }

        Condition condition = new Condition();
        if (id != null && id > 0L) {
            condition.notEqual("id", id);
        }
        condition.equal("number", number);
        int count = count(condition);
        BaseAssert.check(count == 0, "编码【" + number + "】不能重复");
    }

    @Override
    public T getByNumber(String number) throws Exception {
        Condition condition = new Condition();
        condition.equal("number", number);
        T model = getBy(condition);

        if (model != null) {
            // 查询子对象数据
            //for (FieldObject fo : getSubFieldList()) {
            //    fo.setValue(model, getSubData(fo.getJavaType(), model));
            //}

            // 查询分录
            for (Map.Entry<Class<? extends BaseEntry>, FieldObject> entry : getEntryMap().entrySet()) {
                FieldObject fo = entry.getValue();
                fo.setValue(model, getEntry(entry.getKey(), model));
            }
        }

        return model;
    }

    protected void setAutoNumber(T model) throws Exception {
        String billName = getRuleGroup();
        try {
            String path = "/codingRule/inner/getCoding?ruleGroup=" + billName;
            String number = RestUtils.get(ServiceNameEnum.ASEN_SYS.getValue(), path, String.class);
            getEntity().setFieldValue(model, "number", number);
        } catch (Exception e) {
            log.error("设置编码规则报错:", e);
            throw new ServiceException("单据【" + billName + "】未设置编码规则," + e.getMessage());
        }
    }

    protected String getRuleGroup() throws Exception {
        return getModelClass().getName();
    }
}
